package org.jiucheng.magpiebridge.manager.service.impl;

import java.util.List;
import java.util.Objects;

import org.jiucheng.ioc.annotation.Inject;
import org.jiucheng.ioc.annotation.Service;
import org.jiucheng.magpiebridge.manager.dto.OAuth2GithubControlDto;
import org.jiucheng.magpiebridge.manager.entity.OAuth2Control;
import org.jiucheng.magpiebridge.manager.service.IOAuth2ControlService;
import org.jiucheng.plugin.db.IBaseService;
import org.jiucheng.util.StringUtil;

import com.alibaba.fastjson.JSON;

@Service("OAuth2ControlService")
public class OAuth2ControlServiceImpl implements IOAuth2ControlService {
	
    @Inject
    private IBaseService baseService;
    
	@Override
	public OAuth2GithubControlDto getOauth2GithubControlDto() {
        OAuth2Control oAuth2Control = new OAuth2Control();
        oAuth2Control.setCategory(OAuth2Control.Category.GITHUB);
        List<OAuth2Control> list = baseService.list(oAuth2Control);
        if (list != null && !list.isEmpty()) {
        	oAuth2Control = list.get(0);
        	if (oAuth2Control != null && StringUtil.isNotBlank(oAuth2Control.getContent())) {
        		return JSON.parseObject(oAuth2Control.getContent(), OAuth2GithubControlDto.class);
        	}
        }
		return null;
	}
	
	@Override
	public void updateOAuth2GithubControlDto(OAuth2GithubControlDto githubControlDto) {
		if (githubControlDto != null) {
			githubControlDto.setCallback(Objects.toString(githubControlDto.getCallback(), StringUtil.EMPTY));
			githubControlDto.setClientId(Objects.toString(githubControlDto.getClientId(), StringUtil.EMPTY));
			githubControlDto.setClientSecret(Objects.toString(githubControlDto.getClientSecret(), StringUtil.EMPTY));
			if (!"T".equals(githubControlDto.getOpened())) {
				githubControlDto.setOpened("F");
			}
		} else {
			githubControlDto = new OAuth2GithubControlDto();
			githubControlDto.setCallback(StringUtil.EMPTY);
			githubControlDto.setClientId(StringUtil.EMPTY);
			githubControlDto.setClientSecret(StringUtil.EMPTY);
			githubControlDto.setOpened("F");
		}
        OAuth2Control oAuth2Control = new OAuth2Control();
        oAuth2Control.setCategory(OAuth2Control.Category.GITHUB);
        List<OAuth2Control> list = baseService.list(oAuth2Control);
        if (list != null && !list.isEmpty()) {
        	oAuth2Control = list.get(0);
        	oAuth2Control.setContent(JSON.toJSONString(githubControlDto));
        	baseService.update(oAuth2Control);
        } else {
        	oAuth2Control.setContent(JSON.toJSONString(githubControlDto));
        	baseService.save(oAuth2Control);
        }
	}
}
